<template>
  <CoolDialog v-model="showDetailDialog" title="规则链详情" :width="450" destroy-on-close>
    <chain-detail :id="detailsId"></chain-detail>
  </CoolDialog>
  <CoolDialog
    @close="closeAddOrEditDialog"
    v-model="showAddOrEditDialog"
    :width="500"
    :title="dialogTitle"
  >
    <el-form
      :model="addOrEditForm"
      label-width="120px"
      :rules="rules"
      ref="addOrEditFormRef"
    >
      <el-form-item label="规则链名称" prop="name">
        <el-input
          v-model="addOrEditForm.name"
          placeholder="请输入规则链名称"
          show-word-limit
          maxlength="30"
        />
      </el-form-item>
      <el-form-item label="规则链描述">
        <el-input
          v-model="addOrEditForm.info"
          placeholder="请输入规则链描述"
          show-word-limit
          maxlength="64"
        />
      </el-form-item>

      <el-form-item :label="langMsg?.validornot || '是否有效'" prop="mainFlag">
        <el-radio-group v-model="addOrEditForm.mainFlag">
          <el-radio :label="1" style="margin-right: 15px">有效</el-radio>
          <el-radio :label="0">无效</el-radio>
        </el-radio-group>
        <!-- <el-switch
          size="small"
          v-model="addOrEditForm.mainFlag"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch> -->
      </el-form-item>
    </el-form>
    <div style="margin-top: 30px; text-align: center">
      <el-button @click="submit">确定</el-button>
      <el-button @click="closeAddOrEditDialog">{{ langMsg?.cancel || "取消" }}</el-button>
    </div>
  </CoolDialog>
  <com-dialog
    class="confiration-dialog"
    @close="closeConfiguration"
    @ok="submit"
    v-model="showConfiguration"
    fullscreen
    dialogBg="#00071F"
    titleBg="#00071F"
    :hasFooter="false"
    v-if="showConfiguration"
  >
    <Configuration :currChainId="currChainId" class="config-content"></Configuration>
  </com-dialog>
  <el-container class="layout-aside-main">
    <el-main class="page-main">
      <com-operation-row>
        <com-operation-row>
          <el-input
            placeholder="规则链名称"
            prefix-icon="Search"
            v-model="searchForm.name"
            clearable
          >
          </el-input>
          <el-button
            v-if="limitList.queryAtrs.limit"
            type="primary"
            icon="Search"
            @click="getTableData"
          >
            {{ langMsg?.query || "查询" }}
          </el-button>
          <el-button v-if="limitList.addAtrs.limit" @click="openAddDialog">
            <com-icon color="#2a82e4">
              <CirclePlus />
            </com-icon>
            {{ langMsg?.add || "新增" }}
          </el-button>
        </com-operation-row>
        <template #right>
          <el-upload
            class="upload-demo"
            action=""
            :limit="1"
            ref="upload"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="onchange"
            :file-list="fileList"
            accept="json"
          >
            <el-button size="small" type="primary">{{
              langMsg?.import || "导入"
            }}</el-button>
          </el-upload>
          <three-buttons-group
            @refresh="getTableData"
            v-model:headers="tableHeaders"
            ref="threeBtnRef"
            :sortable="false"
            :exportable="false"
          />
        </template>
      </com-operation-row>
      <com-pagination-table
        :loading="tableLoading"
        v-model:current-page="pageObj.current"
        v-model:page-size="pageObj.size"
        @size-or-current-change="getTableData"
        :data="tableData"
        :headers="tableHeaders"
        showPage
        :total="pageObj.total"
      >
        <template #row.mainFlag="{ row }">
          <el-switch
            @change="changeStatus(row)"
            v-model="row.mainFlag"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </template>
        <template #row.action="{ row }">
          <el-button type="primary" size="small" text @click="openConfiguration(row)">{{
            langMsg?.rulechainconfiguration || "组态"
          }}</el-button>
          <el-button
            v-if="limitList.editAtrs.limit"
            type="primary"
            size="small"
            text
            @click="openEditDialog(row)"
            >{{ langMsg?.edit || "编辑" }}</el-button
          >
          <el-button
            v-if="limitList.deleteAtrs.limit"
            type="primary"
            size="small"
            text
            @click="delRuleChain(row.id)"
            >{{ langMsg?.delete || "删除" }}</el-button
          >
          <el-button type="primary" size="small" text @click="openDetailDialog(row)">{{
            langMsg?.details || "详情"
          }}</el-button>
          <el-button type="primary" size="small" text @click="exportARule(row)">{{
            langMsg?.export || "导出"
          }}</el-button>
        </template>
      </com-pagination-table>
    </el-main>
  </el-container>
</template>
<!-- <script>
export default {
  name: 'RuleChain',
}
</script> -->
<script lang="ts" setup>
import ComPaginationTable from "@/components/ComPaginationTable.vue";
import ComOperationRow from "@/components/ComOperationRow.vue";
import { computed, reactive, ref, provide } from "vue";
import type { ComPaginationTableHeader } from "@/interface";
import { DialogType } from "./const";
import { downloadFile } from "@/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus } from "@element-plus/icons-vue";
import CoolDialog from "@/components/CoolDialog.vue";
import ComIcon from "@/components/ComIcon.vue";
import ThreeButtonsGroup from "@/components/ThreeButtonsGroup.vue";
import ComDialog from "@/components/ComDialog.vue";
import Configuration from "./components/Configuration.vue";
import ChainDetail from "./ChainDetail.vue";
// const DebuggerConfiguration = defineAsyncComponent(
//   () => import('./components/DebuggerConfiguration.vue'),
// )

interface LimitInfo {
  name: string;
  limit: boolean;
}
interface LimitButton {
  editAtrs: LimitInfo;
  queryAtrs: LimitInfo;
  deleteAtrs: LimitInfo;
  addAtrs: LimitInfo;
}
interface Props {
  limitList?: LimitButton;
  apis: any;
  showArea: Boolean;
  langMsg?: any;
}
const props = withDefaults(defineProps<Props>(), {
  limitList: () => {
    return {
      editAtrs: {
        name: "编辑",
        limit: true,
      },
      queryAtrs: {
        name: "查询",
        limit: true,
      },
      deleteAtrs: {
        name: "删除",
        limit: true,
      },
      addAtrs: {
        name: "新增",
        limit: true,
      },
    };
  },
  apis: () => {
    return {};
  },
  showArea: () => {
    return true;
  },
  langMsg: () => {
    return {};
  },
});

provide("apis", props.apis);
//显示面积与否
provide("showArea", props.showArea);
provide("langMsg", props.langMsg);
//api
// let apis: any = ref({})
// const importApi = (apis) => {
//   apis.value = apis
//   // let { editRuleChain,
//   //   queryPageRuleChain,
//   //   deleteRuleChain,
//   //   saveRuleChain,
//   //   byIdGetChain,
//   //   exportRule,
//   //   importRule } = apis
// }
// importApi('r')
// 组态
let currentFactId = ref(null);
let currChainId: any = ref(null);
// const showDebugger = ref(false)
// const debuggerConfiguration = (row) => {
//   //调试
//   showDebugger.value = true
//   currentFactId.value = row.factId
//   currChainId.value = row.id
// }

provide("currentFactId", currentFactId);
const showConfiguration = ref(false);
const openConfiguration = (row: any) => {
  showConfiguration.value = true;
  currentFactId.value = row.factId;
  currChainId.value = row.id;
};

const closeConfiguration = () => {
  showConfiguration.value = false;
};
let tableHeaders = reactive<ComPaginationTableHeader[]>([
  {
    type: "index",
    isVisible: true,
    label: props?.langMsg?.serialnumber || "序号",
    align: "center",
    width: "60",
    fixed: true,
  },
  {
    prop: "name",
    isVisible: true,
    label: props?.langMsg?.name || "名称",
    width: "180",
    fixed: true,
  },
  {
    prop: "info",
    isVisible: true,
    label: props?.langMsg?.description || "描述",
    width: "180",
  },
  { prop: "mainFlag", isVisible: true, label: "有效" },
  {
    prop: "updateTime",
    isVisible: true,
    label: props?.langMsg?.updatetime || "更新时间",
    width: 200,
  },
  {
    prop: "action",
    isVisible: true,
    label: props?.langMsg?.operation || "操作",
    width: 330,
  },
]);
const tableLoading = ref(false);
const tableData = reactive<RuleChain[]>([]);
const searchForm = reactive({ name: "" });
const pageObj = reactive({
  size: 20,
  current: 1,
  total: 0,
});
const dialogType = ref(DialogType.add);
const dialogTitle = computed(() =>
  dialogType.value === DialogType.add ? "新增规则链" : "编辑规则链"
);
interface RuleChain {
  id?: number;
  name?: string;
  info?: string;
  factName?: string;
  mainFlag?: number;
  factId?: string;
  updateTime?: string;
  updateUser?: string;
}
const addOrEditFormRef: any = ref();
const addOrEditForm = ref<RuleChain>({
  name: "",
  info: "",
  factName: "",
  mainFlag: 0,
});
const rules = reactive({
  name: [{ required: true, message: "请输入名字", trigger: "blur" }],
});
const showAddOrEditDialog = ref(false);
const openAddDialog = () => {
  dialogType.value = DialogType.add;
  showAddOrEditDialog.value = true;
};
const currHasConfigution = ref(false);
const openEditDialog = async (row: RuleChain) => {
  //在修改之前查看是否已经组态过，若是组过不能更改绑定的对象，若是没组过才可更改
  let res = await props.apis?.byIdGetChain(row.id);
  addOrEditForm.value = res.data.data;
  dialogType.value = DialogType.edit;
  showAddOrEditDialog.value = true;
};
const closeAddOrEditDialog = () => {
  addOrEditForm.value = {};
  showAddOrEditDialog.value = false;
  addOrEditFormRef.value.resetFields();
  currHasConfigution.value = false;
};
const getTableData = async () => {
  tableLoading.value = true;
  tableData.length = 0;
  const r = await props.apis?.queryPageRuleChain({
    size: pageObj.size,
    current: pageObj.current,
    dtoObj: {
      name: searchForm.name,
    },
  });
  tableLoading.value = false;
  // r.data.data.records.map((item: any) => {
  //   item.mainFlag = item.mainFlag == 1 ? true : false;
  // });
  tableData.push(...(r.data.data.records || []));
  pageObj.total = r.data.data.total;
};
const changeStatus = async (row: { id: any; mainFlag: any }) => {
  if (!row.id) return;
  await props.apis?.editRuleChain(row.id, {
    mainFlag: row.mainFlag,
  });
  ElMessage.success("修改成功");
  getTableData();
};
const submit = () => {
  dialogType.value === DialogType.add ? saveChain() : editChain();
};

const saveChain = () => {
  addOrEditFormRef.value.validate(async (valid: any) => {
    if (valid) {
      const r = await props.apis?.saveRuleChain({
        name: addOrEditForm.value.name?.trim(),
        info: addOrEditForm.value.info,
        mainFlag: addOrEditForm.value.mainFlag,
      });
      dialogType.value === DialogType.add
        ? ElMessage.success("添加成功")
        : ElMessage.success("编辑成功");
      closeAddOrEditDialog();
      getTableData();
    }
  });
};
const editChain = () => {
  addOrEditFormRef.value.validate(async (valid: any) => {
    if (valid) {
      await props.apis?.editRuleChain(addOrEditForm.value.id, {
        name: addOrEditForm.value.name?.trim(),
        info: addOrEditForm.value.info,
        mainFlag: addOrEditForm.value.mainFlag,
      });
      ElMessage.success("编辑成功");
      closeAddOrEditDialog();
      getTableData();
    }
  });
};

const delRuleChain = (id: number) => {
  ElMessageBox.confirm("确定删除该规则链吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: props?.langMsg?.cancel || "取消",
    type: "warning",
  })
    .then(async () => {
      await props.apis?.deleteRuleChain(id);
      ElMessage.success("删除成功");
      getTableData();
    })
    .catch(() => {});
};
const threeBtnRef = ref();
const showDetailDialog = ref(false);
const detailsId = ref();
const openDetailDialog = (row: RuleChain) => {
  detailsId.value = row.id;
  showDetailDialog.value = true;
};
const exportARule = async (row: any) => {
  let res = await props.apis?.exportRule(row.id);
  downloadFile(res.data, row.name + ".json");
};

const upload = ref();
const fileList = ref([]);
const onchange = async (file: { name: string; raw: any }) => {
  if (!/\.(json)$/.test(file.name)) {
    ElMessage.error("上传文件只能为json格式");
    fileList.value = [];
    return false;
  }

  await props.apis?.importRule({ file: file.raw });
  ElMessage.success("规则链导入成功!");
  getTableData();
  fileList.value = [];
};
getTableData();
</script>

<style lang="scss" scoped>
@use '@/assets/styles/backstage-management/index.scss';
//@use '@/assets/styles/technology-theme/index.scss';删除technology-theme样式文件夹

.confiration-dialog {
  :deep(.el-dialog) {
    display: flex;
    background-color: #00071f;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    background-color: #00071f;
  }

  :deep(.el-dialog__body) {
    flex: 1;
    min-height: 0;
    padding: 0 10px 10px;
    background-color: #00071f;
  }

  :deep(.el-dialog__footer) {
    background-color: #00071f;
  }

  .config-content {
    :deep(.el-dialog__header) {
      position: absolute !important;
      z-index: 9999;
      height: 32px !important;
      background-color: transparent;
    }
  }
}
</style>
